from ansys.mapdl import reader
import numpy as np


class AnsysParser(object):

    def __init__(self, model_path, result_path):
        self.model = reader.Archive(model_path)
        self.result = reader.read_binary(result_path)

    @property
    def model_info(self):
        info = {
            "component": list(self.result.element_components.keys()),
            "material": list(self.result.materials.keys()),
            "property": self.result.section_data,
        }
        return info

    @property
    def result_info(self):
        columns = [
            "node_id",
            "node_coordx",
            "node_coordy",
            "node_coordz",
            "displacement",
        ]
        node_id = self.result.nodal_displacement(0)[0]
        nodel_coord = self.model.nodes
        nodel_value = self.result.nodal_displacement(0)[1]
        info = []
        for i in range(len(node_id)):
            disp = np.sqrt(np.sum(nodel_value[i]**2))
            info.append(
                {
                    "node_id": node_id[i],
                    "node_coordx": nodel_coord[i][0],
                    "node_coordy": nodel_coord[i][1],
                    "node_coordz": nodel_coord[i][2],
                    "displacement": disp,
                }
            )
        return columns, info